package com.faryangsh.AspectUseSpring;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @author 杨志远[of2551]
 *         company qianmi.com
 *         Date    2017-06-12
 */
@Component
@Aspect
@EnableAspectJAutoProxy
public class RequestMappingInterceptor {

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void restPointcut() {
    }

    @Pointcut("execution(* *(..))")
    public void anyMethodPointcut() {
    }

    @AfterReturning(value = "restPointcut() && anyMethodPointcut()", returning = "response")
    public Object wrapResponse(Object response) {
        Map<String, Object> result = new HashMap<>();
        result.put("status", 1);
        result.put("data", response);
        return result;
    }

    @AfterThrowing(value = "restPointcut() && anyMethodPointcut()", throwing = "exception")
    public Object wrapException(RuntimeException exception) {
        Map<String, Object> result = new HashMap<>();
        result.put("status", 0);
        result.put("msg", exception.getMessage());
        return result;
    }

}
